package com.lvyq.javaprint.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author lvyq 注册表操作
 * @version 1.0
 * Create by 2024-05-11 16:15
 */
public class RegistryUtil {



    /**
     * @description 查询
     * @author lvyq
     * @param[1] key
     * @param[2] name
     * @throws
     * @return String
     * @time 2024-05-11 16:17
     */
    public static String readRegistryValue(String key, String name) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec("reg query \"" + key + "\" /v \"" + name + "\"");
        process.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains(name)) {
                String[] parts = line.split("\\s+");
                if (parts.length > 2) {
                    return parts[parts.length - 1];
                }
            }
        }

        return null;
    }



    /**
     * @description  添加
     * @author lvyq
     * @param[1] key
     * @param[2] name
     * @param[3] value
     * @throws

     * @time 2024-05-11 16:16
     */
    public static int addToRegistry(String key, String name, String value) throws IOException, InterruptedException {
        // 使用 reg add 命令添加键值对到注册表
        Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + name + "\" /d \"" + value + "\" /f");
        return process.waitFor();
    }

    /**
     * @description 移除
     * @author lvyq
     * @param[1] key
     * @param[2] name
     * @throws

     * @time 2024-05-11 16:16
     */
    public static void removeFromRegistry(String key, String name) throws IOException, InterruptedException {
        // 使用 reg delete 命令从注册表中删除键值对
        Process process = Runtime.getRuntime().exec("reg delete \"" + key + "\" /v \"" + name + "\" /f");
        process.waitFor();
    }
}
